import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, message, Space, Pagination } from 'antd';
import { EyeOutlined, CopyOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import promptPlusService from '@/services/prompt-plus';

const PromptTemplateList = () => {
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  const [isViewModalVisible, setIsViewModalVisible] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<API.Template | null>(null);
  const [searchText, setSearchText] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [loading, setLoading] = useState(false);
  const [templates, setTemplates] = useState<API.Template[]>([]);
  const [total, setTotal] = useState(0);
  const [form] = Form.useForm();

  const columns = [
    {
      title: '提示词名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '模板类型',
      dataIndex: 'templateType',
      key: 'templateType',
      render: (text: string) => `[${text}]`,
      filters: [
        { text: '迭代提示词', value: '迭代提示词' },
        { text: '优化提示词', value: '优化提示词' },
      ],
      onFilter: (value: string, record: API.Template) => record.templateType.includes(value),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (text: string) => `[${text}]`,
      filters: [
        { text: '内置', value: '内置' },
        { text: '外部', value: '外部' },
      ],
      onFilter: (value: string, record: API.Template) => record.type.includes(value),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (text: string) => `[${text}]`,
      filters: [
        { text: '选择', value: '选择' },
        { text: '未选择', value: '未选择' },
      ],
      onFilter: (value: string, record: API.Template) => record.status.includes(value),
    },
    {
      title: '最后修改',
      dataIndex: 'lastModified',
      key: 'lastModified',
      sorter: (a: API.Template, b: API.Template) => new Date(a.lastModified).getTime() - new Date(b.lastModified).getTime(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: API.Template) => (
        <Space size="middle">
          <Button
            type="text"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
            title="查看"
          />
          <Button
            type="text"
            icon={<CopyOutlined />}
            onClick={() => handleCopy(record)}
            title="复制"
          />
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            title="编辑"
          />
          <Button
            type="text"
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
            title="删除"
            danger
          />
        </Space>
      ),
    },
  ];

  useEffect(() => {
    loadTemplates();
  }, [currentPage, pageSize, searchText]);

  const loadTemplates = async () => {
    setLoading(true);
    try {
      const res = await promptPlusService.template.getTemplates({
        page: currentPage,
        size: pageSize,
        keyword: searchText,
      });
      setTemplates(res);
      setTotal(res.total || 0);
    } catch (error) {
      message.error('加载提示词模板失败');
      console.error('Error loading templates:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setIsAddModalVisible(true);
  };

  const handleView = (record: API.Template) => {
    setSelectedTemplate(record);
    setIsViewModalVisible(true);
  };

  const handleCopy = (record: API.Template) => {
    navigator.clipboard.writeText(record.content);
    message.success('提示词内容已复制');
  };

  const handleEdit = (record: API.Template) => {
    setSelectedTemplate(record);
    form.setFieldsValue({
      name: record.name,
      templateType: record.templateType,
      content: record.content,
      description: record.description,
      type: record.type,
      status: record.status
    });
    setIsEditModalVisible(true);
  };

  const handleDelete = async (record: API.Template) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除提示词 "${record.name}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      async onOk() {
        try {
          await promptPlusService.template.deleteTemplate(record.id);
          message.success('提示词已删除');
          loadTemplates();
        } catch (error) {
          message.error('删除提示词失败');
          console.error('Error deleting template:', error);
        }
      },
    });
  };

  const handleAddOk = async () => {
    try {
      const values = await form.validateFields();
      await promptPlusService.template.addTemplate({
        ...values,
        lastModified: new Date().toISOString(),
      });
      message.success('提示词添加成功');
      form.resetFields();
      setIsAddModalVisible(false);
      loadTemplates();
    } catch (error) {
      console.error('Validate Failed:', error);
    }
  };

  const handleEditOk = async () => {
    try {
      const values = await form.validateFields();
      if (selectedTemplate) {
        await promptPlusService.template.updateTemplate(selectedTemplate.id, {
          ...values,
          lastModified: new Date().toISOString(),
        });
        message.success('提示词修改成功');
        form.resetFields();
        setIsEditModalVisible(false);
        loadTemplates();
      }
    } catch (error) {
      console.error('Validate Failed:', error);
    }
  };

  const handleAddCancel = () => {
    form.resetFields();
    setIsAddModalVisible(false);
  };

  const handleEditCancel = () => {
    form.resetFields();
    setIsEditModalVisible(false);
  };

  const handleViewCancel = () => {
    setIsViewModalVisible(false);
  };

  const copyContent = () => {
    if (selectedTemplate) {
      navigator.clipboard.writeText(selectedTemplate.content);
      message.success('内容已复制');
    }
  };

  const handlePageChange = (page: number, newPageSize: number) => {
    setCurrentPage(page);
    setPageSize(newPageSize);
  };

  const modalForm = (
    <Form form={form} layout="vertical">
      <Form.Item
        name="name"
        label="提示词名称"
        rules={[{ required: true, message: '请输入提示词名称' }]}
      >
        <Input placeholder="例如：通用优化" />
      </Form.Item>

      <Form.Item
        name="templateType"
        label="模板类型"
        rules={[{ required: true, message: '请选择模板类型' }]}
      >
        <Select placeholder="选择模板类型">
          <Select.Option value="迭代提示词">迭代提示词</Select.Option>
          <Select.Option value="优化提示词">优化提示词</Select.Option>
        </Select>
      </Form.Item>

      <Form.Item
        name="type"
        label="类型"
        rules={[{ required: true, message: '请选择类型' }]}
      >
        <Select placeholder="选择类型">
          <Select.Option value="内置">内置</Select.Option>
          <Select.Option value="外部">外部</Select.Option>
        </Select>
      </Form.Item>

      <Form.Item
        name="status"
        label="状态"
        rules={[{ required: true, message: '请选择状态' }]}
      >
        <Select placeholder="选择状态">
          <Select.Option value="选择">选择</Select.Option>
          <Select.Option value="未选择">未选择</Select.Option>
        </Select>
      </Form.Item>

      <Form.Item
        name="content"
        label="提示词内容"
        rules={[{ required: true, message: '请输入完整的提示词内容' }]}
      >
        <Input.TextArea rows={12} placeholder="请输入完整的提示词内容..." />
      </Form.Item>

      <Form.Item
        name="description"
        label="描述"
      >
        <Input.TextArea rows={3} placeholder="简要描述提示词的用途..." />
      </Form.Item>
    </Form>
  );

  return (
    <div style={{ padding: '20px' }}>
      <div style={{
        marginBottom: '16px',
        display: 'flex',
        justifyContent: 'flex-end',
        gap: '16px'
      }}>
        <Input
          placeholder="搜索提示词"
          prefix={<SearchOutlined />}
          style={{ width: 300 }}
          value={searchText}
          onChange={(e) => {
            setSearchText(e.target.value);
            setCurrentPage(1);
          }}
          allowClear
        />
        <Button type="primary" onClick={handleAdd}>
          添加提示词
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={templates}
        bordered
        pagination={false}
        loading={loading}
        rowKey="id"
      />

      <div style={{
        marginTop: 16,
        display: 'flex',
        justifyContent: 'flex-end'
      }}>
        <Pagination
          current={currentPage}
          pageSize={pageSize}
          total={total}
          onChange={handlePageChange}
          onShowSizeChange={handlePageChange}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条`}
        />
      </div>

      {/* Add Prompt Modal */}
      <Modal
        title="添加提示词"
        open={isAddModalVisible}
        onOk={handleAddOk}
        onCancel={handleAddCancel}
        okText="确认"
        cancelText="取消"
        width={700}
        bodyStyle={{ height: '600px', overflowY: 'auto' }}
      >
        {modalForm}
      </Modal>

      {/* Edit Prompt Modal */}
      <Modal
        title="编辑提示词"
        open={isEditModalVisible}
        onOk={handleEditOk}
        onCancel={handleEditCancel}
        okText="确认"
        cancelText="取消"
        width={700}
        bodyStyle={{ height: '600px', overflowY: 'auto' }}
      >
        {modalForm}
      </Modal>

      {/* View Prompt Modal */}
      <Modal
        title="查看提示词内容"
        open={isViewModalVisible}
        onCancel={handleViewCancel}
        footer={[
          <Button key="copy" type="primary" onClick={copyContent} icon={<CopyOutlined />}>
            复制内容
          </Button>,
          <Button key="cancel" onClick={handleViewCancel}>
            取消
          </Button>,
        ]}
        width={700}
        bodyStyle={{ maxHeight: '600px', overflowY: 'auto' }}
      >
        {selectedTemplate && (
          <div>
            <p><strong>提示词名称：</strong>{selectedTemplate.name}</p>
            <p><strong>模板类型：</strong>{selectedTemplate.templateType}</p>
            <p><strong>类型：</strong>{selectedTemplate.type}</p>
            <p><strong>状态：</strong>{selectedTemplate.status}</p>
            <p><strong>最后修改：</strong>{new Date(selectedTemplate.lastModified).toLocaleString()}</p>
            <p><strong>提示词内容：</strong></p>
            <pre style={{
              background: '#f5f5f5',
              padding: '16px',
              borderRadius: '4px',
              whiteSpace: 'pre-wrap',
              wordWrap: 'break-word'
            }}>
              {selectedTemplate.content}
            </pre>
            {selectedTemplate.description && (
              <p><strong>描述：</strong>{selectedTemplate.description}</p>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default PromptTemplateList;
